package com.ys.controller.api.finance;

import com.alibaba.fastjson.JSONObject;
import com.ys.entity.finance.TcwFinancesApiInFo;
import com.ys.entity.finance.TcwFinancesEventGroups;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.business.YsbExportLogService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/tcwFinancesApiInFo")
public class ApiInterTcwFinancesApiInFoController {
	private static Long MENU_ID = 82L; // TODO

//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	private Object lock = new Object();
	
	@Autowired
	private CommonApiService<TcwFinancesApiInFo> commonApiService;

	@Autowired
	private YsbExportLogService ysbExportLogService;

	@RequiresPermissions("tcwFinancesApiInFo:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TcwFinancesApiInFo cond){
		cond
		.where("A.Type != 'Transfer'")
		.setOrderby("A.PurchaseDate desc");
		LayuiTableVoJA vo = commonApiService.searchLay(cond);
		{
			JSONObject JO = new JSONObject();
			// 订单总金额累计
			JO.put("total", cond.setFields("ISNULL(SUM(A.Total),0)").sumDecimal());

			vo.setTotalRow(JO);
		}
		return vo;
	}

	@RequestMapping("/export")
	@ResponseBody
	public R export(@ModelAttribute TcwFinancesApiInFo cond, String conditions) throws Exception{
		synchronized (lock) {
			YsbExportLogService.ExportDto dto1 = ysbExportLogService.init(MENU_ID);
			cond
					.where("A.Type != 'Transfer'")
					.setPage(0).setSize(99999);

			//获取数据
			List<Map<String, Object>> listData = cond.queryMap();


			List<YsCol> listField = new YsCol()
					.setMenuId(MENU_ID)
					.setFrontShow(YsColEnum.FrontShow.SHOW.value)
					.setOrderby("A.SortNo asc")
					.queryList();


			ExportExcelUtils<TcwFinancesEventGroups> util = new ExportExcelUtils<TcwFinancesEventGroups>(new TcwFinancesEventGroups());

			String toFilePath = util.exportExcel(listData, listField, "财务事件表(按SKU)");
			UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
			ysbExportLogService.updateSuccess(dto1.getId(), dto.getUrl());
			Thread.sleep(20000L);
			return R.ok("已经生成完毕");
		}
	}
}
